﻿export const
    EXPANDED = 'expanded',
    CHECKED = 'checked',
    DEPARTMENTS = 'departments',
    SECTIONS = 'sections',
    TEACHERS = 'teachers';

export function replace(arr, oldItem, newItem) {
    var index = arr.indexOf(oldItem);
    if (index > -1) {
        return [...arr.slice(0, index), newItem, ...arr.slice(index + 1)];
    } else {
        return arr;
    }
}

export function reverse(obj, boolAttr) {
    return {
        ...obj,
        [boolAttr]: !obj[boolAttr]
    }
}
export function reverseChecked(obj) { return reverse(obj, CHECKED) }
export function reverseExpanded(obj) { return reverse(obj, EXPANDED) }

export function buildParent(parent, arrName, oldItem, newItem) {
    return {
        ...parent,
        [arrName]: replace(parent[arrName], oldItem, newItem)
    }
}

// note: this function return new created college, not the whole state
export function expand(college, dep, sec) {
    if (!dep)   // expand college
        return reverseExpanded(college);
    if (!sec)   // expand department
        return buildParent(college, DEPARTMENTS, dep, reverseExpanded(dep));
    else {      // expand section
        const newDep = buildParent(dep, SECTIONS, sec, reverseExpanded(sec));
        return buildParent(college, DEPARTMENTS, dep, newDep);
    }
}

